package com.draven.mall.controller;

import com.draven.mall.common.ApiResponse;
import com.draven.mall.entity.Order;
import com.draven.mall.service.OrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/user/order")
public class UserOrderController {

    private static final Logger log = LoggerFactory.getLogger(UserOrderController.class);

    @Autowired
    private OrderService orderService;

    /**
     * 用户对骑手进行评分
     */
    @PostMapping("/rate-rider")
    public ApiResponse rateRider(
            @RequestParam Long orderId,
            @RequestParam Long riderId,
            @RequestParam Float rating,
            @RequestParam(required = false) String comment) {
        try {
            // 验证评分范围
            if (rating < 1 || rating > 5) {
                return ApiResponse.error("评分必须在1-5之间");
            }
            
            // 验证订单是否存在且已完成
            Order order = orderService.getOrderById(orderId);
            if (order == null) {
                return ApiResponse.error("订单不存在");
            }
            
            if (order.getRiderId() == null || !order.getRiderId().equals(riderId)) {
                return ApiResponse.error("该骑手未配送此订单");
            }
            
            if (order.getStatus() != 3) { // 假设状态3为已完成
                return ApiResponse.error("订单尚未完成，无法评价");
            }
            
            // 保存评价
            boolean success = orderService.rateRider(orderId, riderId, rating, comment);
            if (success) {
                return ApiResponse.success("评价成功");
            } else {
                return ApiResponse.error("评价失败");
            }
        } catch (Exception e) {
            log.error("评价骑手异常", e);
            return ApiResponse.error("评价失败: " + e.getMessage());
        }
    }
} 